package com.etoak.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import com.etoak.common.core.enums.OrderStateEnum;
import com.etoak.common.web.context.LoginUserContext;
import com.etoak.config.OrderQueueConfig;
import com.etoak.dto.OrderDto;
import com.etoak.entity.Order;
import com.etoak.mapper.OrderMapper;
import com.etoak.service.OrderItemService;
import com.etoak.service.OrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author etoak
 * @since 2025-08-28
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {

    @Autowired
    RabbitTemplate rabbitTemplate;

    @Autowired
    OrderItemService orderItemService;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void create(OrderDto orderDto) {
        String orderNo= IdUtil.getSnowflakeNextIdStr();

        Order order = new Order();
        order.setOrderNo(orderNo);
        order.setUserId(Integer.parseInt(LoginUserContext.getUserId()));
        order.setOrderState(OrderStateEnum.NEW.getValue());
        order.setPrepareTime(orderDto.getPrepareTime());
        order.setCreateTime(DateUtil.now());

        this.save(order);
        //给订单设置订单编号
        orderDto.getItemList().forEach(item->item.setOrderNo(orderNo));
        //批量保存
        orderItemService.saveBatch(orderDto.getItemList());

        rabbitTemplate.convertAndSend(OrderQueueConfig.EXCHANGE,OrderQueueConfig.KEY,orderNo,
        message -> {
            message.getMessageProperties().setDelayLong(1000*10L);
            return message;
        });
    }
}
